//author:jxx
//此处是对表单的方法，组件，权限操作按钮等进行任意扩展(方法扩展可参照SellOrder.js)
import { data } from "jquery";
import gridFooter from "./product/Mall_distri_good.vue";
let extension = {
  components: {//动态扩充组件或组件路径
    //表单header、content、footer对应位置扩充的组件
    gridHeader: '',//{ template: "<div>扩展组xx件</div>" },
    gridBody: () => import("./product/membershipBenefits.vue"),//会员优惠弹窗
    gridFooter: gridFooter,
    //弹出框(修改、编辑、查看)header、content、footer对应位置扩充的组件
    modelHeader: '',
    modelBody: '',
    modelFooter: ''
  },
  buttons: { view: [], box: [], detail: [] },//扩展的按钮
  methods: {//事件扩展
    //根据分销商ID获取分销商的详细信息
    getModel(val) {
      this.editFormFields.status = "";
      this.editFormFields.code = "";
      let distriPattern = this.getFormOption('distriPattern'); // 分销模式
      this.http.get("api/distriProducts/GetDistributors?id=" + val, {}, true).then(reslut => {
        if (reslut) {
          this.editFormFields.status = reslut.data.status;
          //var statusOption = this.getFormOption('status');
          //statusOption.style="color:#c5242c";
          // let time = new Date().getTime();
          // let endtime = new Date(reslut.distributorEndTime).getTime();
          // let starttime = new Date(reslut.distributorStartTime).getTime();
          // if (time >= starttime && time <= endtime) {
          //     this.editFormFields.status = reslut.data;
          //     var code = this.getFormOption('status');
          //     this.$set(code, "color", "blue")
          // } else {
          //     this.editFormFields.status = "已过期";
          //     var code = this.getFormOption('status');
          //     this.$set(code, "color", "red")
          // }
          this.editFormFields.code = reslut.data.distributorCode;
          let producttypeOption = this.getFormOption("producttype");//产品类型
          producttypeOption.disabled = false
          //var selectOption = this.getFormOption('productid');
          //this.$set(selectOption, "disabled", false)
          if (reslut.data.distributorType == 2002) {
            distriPattern.hidden = false;
          } else {
            distriPattern.hidden = true;
            // this.editFormFields.distriPriceOrRatio =
          }
        }
      });
    },
    getProductModel(val) {//根据产品ID获取产品下所有商品
      this.$refs.detail.reset()
      let isEDIT = this.currentAction == this.const.EDIT;
      if (!isEDIT) {
        this.http.get("api/distriProducts/getGoods?id=" + val, {}, true).then(reslut => {
          //let data=[];
          this.editFormFields.supplierid = reslut.data.disCode;
          reslut.data.goodList.forEach(item => {
            let dataitem = {};
            dataitem.spare1 = item.name;
            dataitem.spare2 = item.code;
            dataitem.spare7 = item.spare7;
            dataitem.goodid = item.goodId;
            dataitem.sellingPrice = item.originalPrice;
            dataitem.preferentialPrice = item.preferentialPrice;
            dataitem.vipPrice = 0;
            dataitem.settlementPrice = 0;
            dataitem.channelPrice = 0;
            dataitem.offlineCode = item.offlineCode;
            dataitem.isAvailable = 1;
            this.$refs.detail.addRow(dataitem);
          })
          //this.detailOptions.data=data;
        });
      }
    },
    getModeltype(val) {//根据分销商ID获取分销商的详细信息
      this.editFormFields.status = "";
      this.http.post("api/distriProducts/GetDistributors?id=" + val, "", true).then(reslut => {
        let datas = [];
        reslut.data.forEach(item => {
          let items = {};
          items.value = item.name;
          items.key = item.code;
          datas.push(items)
        })
        selectOption.data = datas;
      })
    },
    addMemberOffer(row) {
      this.$refs.detail.rowData[row.index].spare6 = JSON.stringify(row.spare6)
    },
    onInit() {
      this.maxBtnLength = 5;
      this.boxOptions.height = 610;
      this.boxOptions.width = 1100;
      this.pagination.sortName = "createDate";  //设置排序字段
      this.pagination.order = "desc"; //排序方式desc或者asc
      let productid = this.getFormOption('productid');//产品名称
      let distributionid = this.getFormOption('distributionid');//分销商
      let producttypeOption = this.getFormOption("producttype");//产品类型
      let isPreSale = this.getFormOption("isPreSale");//是否预售
      let afewdaysahead = this.getFormOption("afewdaysahead");//提前几天售卖
      let timeContainer = this.getFormOption("timeContainer");
      this.editFormFields.isPreSale = 0
      this.editFormFields.auditStatus = 0
      this.editFormFields.periodTicket = 0
      this.searchFormFields.effectiveState = "0"
      distributionid.onChange = (val, item) => {
        this.getModel(val);
      }
      let supplierid = this.getFormOption('supplierid');
      supplierid.onChange = (val, item) => {
      }
      isPreSale.onChange = (val, item) => {
        if (val === 1) {
          afewdaysahead.hidden = false;
          afewdaysahead.required = true;
        }
        else {
          afewdaysahead.hidden = true;
          afewdaysahead.required = false
          delete afewdaysahead.min
        }
      }
      let code = this.getFormOption('code');
      this.$set(code, "disabled", true)
      let status = this.getFormOption('status');
      this.$set(status, "disabled", true)
      this.detailOptions.buttons = [];//去掉子表添加上删除行按钮
      productid.onChange = (val, item) => {
        if (val === undefined) { } else {
          this.getProductModel(val);
        }
      }
      // producttypeOption.changeOnSelect = false;
      // producttypeOption.formatter = nodeArr => {
      //     if (!nodeArr.length) {
      //         return "";
      //     }
      //     return nodeArr[nodeArr.length - 1];
      // };
      producttypeOption.onChange = (val, selectdata) => {
        // this.editFormFields[productid.field] = "";
        productid.type = 'select'
        this.editFormFields.productid = "";
        this.$refs.detail.reset(); //清空从表
        // console.log("kkk", val, this.editFormFields);
        if (val.length == 0) {

        } else {
          this.getProduct(val[val.length - 1])
        }
      }

      // this.editFormFields.productid = [];
      // this.maxBtnLength = 5;
      // var selectOption = this.getFormOption('id');
      //  selectOption.onChange = (val,item)=>{
      //      this.getModeltype(val);
      // }
      let isEDIT = this.currentAction == this.const.EDIT;
      if (isEDIT) {
        this.editFormOptions.forEach(item => {
          item.forEach(x => {
            //如果是编辑帐号设置为只读
            if (x.field == "productid" || x.field == "typeName" || x.field == 'producttype') {
              //disabled是editFormOptions的动态属性，这里只能通过this.$set修改值
              x.disabled = true;
            }
            // if (x.field == "spare1") {
            //     //disabled是editFormOptions的动态属性，这里只能通过this.$set修改值
            //     this.$set(x, "disabled", isEDIT)
            // }
            if (x.field == "distributionid") {
              //disabled是editFormOptions的动态属性，这里只能通过this.$set修改值
              this.$set(x, "disabled", isEDIT)
            }
            if (x.field == "typeName") {
              //disabled是editformOptions的动态属性，这里只能通过this.$set修改值
              this.$set(x, "disabled", isEDIT)

            }
          })
        })
      }
      this.columns.push({
        title: '操作',
        fixed: 'right',
        width: 100,
        render: (h, { row, column, index }) => {
          return h(
            "div", { style: {} }, [
            h(
              "a", {
              props: {},
              style: { "margin-left": "10px" },
              on: {
                click: (e) => {
                  // console.log(row, "----")
                  this.$router.push({
                    name: "V_productbydate",
                    params: {
                      id: row.id,
                      type: 1
                    }
                  })
                }
              }
            },
              "价格日历"
            ),
          ])
        }
      })
      this.detail.columns.push({
        title: "操作", width: 100, align: "center", render: (h, { row, column, index }) => {
          return h(
            "div",
            { style: {} },
            [h(
              "Button",
              {
                style: { "margin-right": "10px" },
                on: {
                  click: (e) => {
                    this.$refs.gridBody.open(row, 2, index)
                  }
                }
              },
              "会员优惠"
            ),
            ],
          )
        }
      })
      // var effectiveStartDate = this.getFormOption('effectiveStartDate');
      //     var effectiveEndDate = this.getFormOption('effectiveEndDate');
      //     effectiveStartDate.onChange = (val, item) => {
      //       effectiveEndDate.min=val;
      //     }
      //     effectiveEndDate.onChange = (val, item) => {
      //       effectiveStartDate.max=val;
      //     }
    },
    rowClick({ row, column, event }) { //查询界面table点击行选中当前行
      // console.log(row,"row")
      let where = {
        sort: "id",
        value: row.id
      };
      this.$refs.gridFooter.$refs.tableList.load(where)
      this.$refs.table.$refs.table.toggleRowSelection(row);
      let selection = row.distributionid;
      this.$refs.gridFooter.distributionid = selection
      if (this.$refs.table.getSelected().length > 1) {
        this.$refs.gridFooter.$refs.tableList.reset()
      }
      setTimeout(() => {
        this.distributionType(selection)
      },0)
      return true;
    },
    // 查询分销商类型,进行判断是否显示分享码
    distributionType(val){
      let param = {
        page: 1,
        rows: 100000,
        sort: "createDate",
        order: "desc",
        wheres: `[{\"name\":\"distributorCode\",\"value\":\"${val}\",\"displayType\":\"text\"}]`
      };
      this.http.post("api/Distributors/GetDistributorList",param, true).then(reslut => {
        console.log(reslut,"reslut")
        if(reslut.rows.length>0){
          this.$refs.gridFooter.distributionTypes(reslut.rows[0].distributorType)
        }
      })

    },
    getFormOption(field) {
      let option;
      this.editFormOptions.forEach(x => {
        x.forEach(item => {
          if (item.field == field) {
            option = item;
          }
        })
      })
      return option;
    },
    modelOpenAfter(row) {
      let isEDIT = this.currentAction == this.const.EDIT;
      //点击弹出框后，如果是编辑状态，禁止编辑帐号，如果新建状态，将帐号字段设置为可编辑
      this.editFormOptions.forEach(item => {
        item.forEach(x => {
          //如果是编辑帐号设置为只读
          if (x.field == "productid") {
            //disabled是editFormOptions的动态属性，这里只能通过this.$set修改值
            this.$set(x, "disabled", true)
          }
          // if (x.field == "spare1") {
          //     //disabled是editFormOptions的动态属性，这里只能通过this.$set修改值
          //     this.$set(x, "disabled", isEDIT)
          // }
          if (x.field == "distributionid") {
            //disabled是editFormOptions的动态属性，这里只能通过this.$set修改值
            this.$set(x, "disabled", isEDIT)
          }

          // if(x.field=="typeCode"){
          //     //disabled是editformOptions的动态属性，这里只能通过this.$set修改值
          //     this.$set(x,"disabled",isEDIT)
          // }
        })
      })
      let timeContainer = this.getFormOption("timeContainer");
      timeContainer.onChange = (val, item) => {
        if (val[1].slice(-8) === '00:00:00') {
          val[1] = val[1].slice(0, -8) + '23:59:59'
        }
        if (val[0] != '' && val[1] != '') {
          let hyn = new Date(val[0]).setFullYear(new Date(val[0]).getFullYear() + 1)  //一年之后的时间
          let hyn2 = new Date(val[1]).getTime()   //选择的时间
          if (hyn2 > hyn) {
            this.$Message.error("起止日期不能超过一年")
            this.editFormFields.timeContainer = []
          }
        }
      }
      let producttypeOption = this.getFormOption("producttype");//产品类型
      let typeNameOption = this.getFormOption("typeName");
      let productName = this.getFormOption("productName");
      let productid = this.getFormOption('productid');//产品名称
      if (!isEDIT) {
        this.$set(producttypeOption, "hidden", false)
        this.$set(typeNameOption, "hidden", true)
        producttypeOption.required = true
        this.editFormFields.spare1 = 0
        this.editFormFields.isSellLikeHot = 0;
        this.editFormFields.isPreSale = 0;
        this.editFormFields.auditStatus = 0
        this.editFormFields.periodTicket = 0
        this.editFormFields.isShowRackrate = 1
        this.editFormFields.isDepositFree = 0
        let sellingRulesid = this.getFormOption("sellingRulesid");
        let refundrulesid = this.getFormOption("refundrulesid");
        let verificationrulesid = this.getFormOption("verificationrulesid");
        console.log(sellingRulesid.data[0],"sellingRulesid")

        this.editFormFields.sellingRulesid=sellingRulesid.data[0].key
        this.editFormFields.refundrulesid=refundrulesid.data[0].key
        this.editFormFields.verificationrulesid=verificationrulesid.data[0].key
      } else {
        // console.log("编辑")
        this.editFormFields.producttype = [row.typeCode]
        this.editFormFields.timeContainer = [row.effectiveStartDate, row.effectiveEndDate]
        this.$set(producttypeOption, "hidden", true)
        this.$set(typeNameOption, "hidden", false)
        this.$set(productid, "hidden", true)
        this.$set(productName, "hidden", false)
        producttypeOption.required = false
        typeNameOption.disabled = true
        this.getModel(this.currentRow.distributionid)
        this.editFormFields.auditStatus = row.auditStatus == 1 ? 0 : 1
      }
      let afewdaysahead = this.getFormOption("afewdaysahead");//提前几天售卖
      if (this.editFormFields.isPreSale === 1) {
        afewdaysahead.hidden = false;
        afewdaysahead.required = true;
      } else {
        afewdaysahead.hidden = true;
        afewdaysahead.required = false;
        delete afewdaysahead.min
      }
      this.changePattern(row);
      this.$set(producttypeOption, "disabled", true)
    },
    searchAfter(rows) {
      //页面加载或者刷新数据后直接显示第一行的明细
      if (rows.length) {
        this.$refs.gridFooter.distributionid =
        rows[0].distributionid;
        let where = {
          sort: "id",
          value: rows[0].id
        };
        this.$refs.gridFooter.$refs.tableList.load(where)

      } else {
        //没有数据时，清空明细数据
        this.$refs.gridFooter.$refs.tableList.reset()
      }
      return true;
    },
    addBefore(formData) { //新建保存前formData为对象，包括明细表
      return this.veriFromTable(formData)
    },
    updateBefore(formData) { //编辑保存前formData为对象，包括明细表、删除行的Id
      return this.veriFromTable(formData)
    },
    // 根据产品类型获取产品名称下拉框数据
    getProduct(val) {
      this.editFormFields.productid = ''
      this.http.get("api/distriProducts/GetProducts?id=" + val + "&distriCode=" + this.editFormFields.code, "", true).then(reslut => {
        let productid = this.getFormOption("productid");
        let productName = this.getFormOption("productName");
        productid.data = [];
        reslut.data.forEach(item => {
          let items = {};
          items.value = item.dicName;
          items.key = item.dicValue;
          productid.data.push(items)
        })
        this.$nextTick(()=>{
          if (reslut.data.length > 0) {
            productid.disabled = false
            productid.hidden = false
            productName.hidden = true
          } else {
            productid.disabled = true
            productid.hidden = true
            productName.hidden = false
          }
        })
      })
    },
    // 保存前编辑
    veriFromTable(formData) {
      console.log("保存前编辑", formData);
      formData.mainData.typeCode = formData.mainData.producttype
      let distriPattern = this.getFormOption('distriPattern'); // 分销模式
      if (distriPattern.hidden) {
        formData.mainData.distriPattern = 0
      }
      if (formData.mainData.distriPattern == 0) {
        formData.mainData.distriPriceOrRatio = null
        formData.mainData.firstCommission = null
        formData.mainData.secondCommission = null
      }
      let timeContainer = formData.mainData.timeContainer.split(",")
      if (timeContainer.length > 0 && timeContainer[0] != "") {
        formData.mainData.effectiveStartDate = timeContainer[0]
        formData.mainData.effectiveEndDate = timeContainer[1]
      } else {
        this.$Message.error("请选择有效起止日期！")
      }

      // 根据商品查询售价
      let st = formData.detailData.filter(i => {
        if (i.preferentialPrice == 0 || i.settlementPrice == 0) {
          return i
        }
      })

      if (st.length != 0) {
        let arr = ''
        st.forEach(i => {
          arr += `商品名称为${i.spare1}的售价为${i.preferentialPrice},结算价为${i.settlementPrice}。`
          if (i.preferentialPrice == 0) {
            i.preferentialPrice = i.settlementPrice;
          }
        })
        if (arr) {
          alert(arr)
        }
      }
      let smallPice = false;
      if (formData.detailData.length) {
        formData.detailData.forEach((item) => {
          if (item.settlementPrice < formData.mainData.secondCommission || item.settlementPrice < formData.mainData.firstCommission) {
            smallPice = true;
          }
        })
      }
      if (formData.mainData.producttype == "" && formData.mainData.typeName == "") {
        this.$Message.error("请选择产品类型")
      } else if (formData.mainData.productid == "" || !formData.mainData.productid) {
        this.$Message.error("请选择产品名称")
      } else if (formData.detailData.length < 1) {
        this.$Message.error("请选择有商品的产品名称！")
        return false
      } else if(smallPice) {
        this.$Message.error("分销佣金不可大于商品结算价！")
        return false
      } else {
        return true
      }
    },
    changePattern (row) {
      let distriPattern = this.getFormOption('distriPattern'); // 分销模式
      let secondCommission = this.getFormOption('secondCommission');
      let firstCommission = this.getFormOption('firstCommission');
      let distriPriceOrRatio = this.getFormOption('distriPriceOrRatio');
      distriPriceOrRatio.hidden = true;
      secondCommission.hidden = true;
      firstCommission.hidden = true;
      this.editFormFields.distriPriceOrRatio = 1;
      this.editFormFields.distriPattern = 0;
      distriPattern.onChange = (val) => {
        if (val == 1) {
          distriPriceOrRatio.hidden = false;
          secondCommission.hidden = false;
          firstCommission.hidden = false;
          this.editFormFields.secondCommission = 0;
          this.editFormFields.firstCommission = 0;
        } else {
          distriPriceOrRatio.hidden = true;
          secondCommission.hidden = true;
          firstCommission.hidden = true;
        }
      }
      if (row) {
        this.getModel(row.distributionid)
        console.log(row,'row');
        if (row.distriPattern == 1) {
          this.editFormFields.distriPattern = row.distriPattern;
          this.editFormFields.distriPriceOrRatio = row.distriPriceOrRatio;
          distriPriceOrRatio.hidden = false;
          secondCommission.hidden = false;
          firstCommission.hidden = false;
        }
      } else {
        distriPattern.hidden = true;
      }
    },
  },
};
export default extension;
